/**   
* @Title: WebGoodsController.java 
* @Package com.txby.platformApi.component.web 
* @Description: 商城商品控制层
* @author Administrator
* @date 2017年11月2日 下午4:07:49 
* @version V1.0   
*/
package com.txby.platformApi.component.web;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.txby.pf.common.utils.PageUtils;
import com.txby.pf.common.utils.Query;
import com.txby.pf.common.utils.R;
import com.txby.platformApi.component.service.WebBaseGoodsService;
import com.txby.platformCore.entity.shop.BaseGoods;

/** 
* @ClassName: WebGoodsController 
* @Description: 商城商品类 
* @author Administrator
* @date 2017年11月2日 下午4:07:49 
*  
*/
@RestController
@RequestMapping("/web/basegoods")
public class WebBaseGoodsController extends CommonController {

	@Resource
	public WebBaseGoodsService webBaseGoodsService;
	
	@RequestMapping("/list")
	@RequiresPermissions("sp:goods:info")
	public R list(@RequestParam Map<String, Object> params){
//		数据隔离
		String sql=getSql();
		String name=params.get("name")==null?"":params.get("name").toString();
		if(!ChkUtil.isEmptyAllObject(name)){
			if (name.contains("%") || name.contains("_")) {
				name = name.trim().replace("%", "\\%").replace("_", "\\_");
				name = "%" + name + "%";
				sql += " and bg.name like #{pojo.name} escape '\\'";
				params.put("name", "%" + name.trim() + "%");
			} else {
				name = "%" + name.trim() + "%";
				sql += " and bg.name like #{pojo.name} ";
				params.put("name", "%" + name.trim() + "%");
			}
		}
		sql += Query.getLastSortSql(params, " order by bg.updateTime ");
		//查询列表数据
		PageList<Map> pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, Query.getPageBean(params), params);
		PageUtils pageUtil = new PageUtils(pl.getResultList(), pl.getPageBean().getTotalCount().intValue(),  pl.getPageBean().getPageSize(), pl.getPageBean().getPage());
		return R.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 查询信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("sp:goods:info")
	public R info(@PathVariable("id") String id){
		String sql=getSql();
	    sql=sql+ " and bg.id_='"+id+"'" ;
		Map goods =  (Map) this.mBaseDao.findBySqlUniqueObject(sql, Map.class, null);
		return R.ok().put("goods", goods);
	}
	
	private String getSql() {
		String sql="select bg.id_,bg.goodsTypeId,bg.keyName,bg.introDetail,bg.introNotice,bg.introState,bg.publishTime,bg.downTime,bg.isDown,bg.isDown sellStatus,bg.name,bg.price,bg.shopsId,bg.unit,s.name shopsName, " 
				 + "n.id_ stockId,n.stockNum,n.residueNum,n.ordersOutNum,r.goodsPicId,pic.url from t_txby_sp_baseGoods bg join t_txby_sp_goodsStockNum n ON "
				 + " bg.id_ = n.goodsId and bg.goodsTypeId=n.goodsTypeId and bg.shopsId=n.shopsId "
				 + " join t_txby_sp_goodsPicRealation r on bg.id_=r.goodsId and bg.goodsTypeId=r.goodsTypeId JOIN "
				+ " t_txby_sp_goodsPic pic on r.goodsPicId=pic.id_ join t_txby_sp_shops s on bg.shopsId=s.id_ where 1=1 ";
		return sql;
	}
	
	/**
	 * 保存库存
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@RequiresPermissions("sp:goods:save")
	public R save(@RequestBody Map map){
		try {
			String userId=getUserId().toString();
			webBaseGoodsService.saveBaseGoods(map,userId);
		} catch (Exception e) {
			return R.error(5000,e.getMessage());
		}
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@RequiresPermissions("sp:goods:update")	
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public R update(@RequestBody  Map map){
		try {
			String name=map.get("name")+"";
			Long id_=Long.valueOf(map.get("id_")+"");
			String userId=getUserId().toString();
			String sql="select * from "+this.mBaseDao.tableName(BaseGoods.class)+" where name ='"+name+"' and id_!="+id_+" ";
			BaseGoods old=(BaseGoods) this.mBaseDao.findBySqlUniqueObject(sql, BaseGoods.class, null);
			if(old!=null){
				return R.ok().error("该商品已存在");
			}else{
				webBaseGoodsService.updateBaseGoods(map,userId);
			}
			
		}catch (Exception e) {
			return R.error(5000,e.getMessage());
		}
		return R.ok();
	}
	
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sp:goods:delete")
	public R delete(@RequestBody String[] ids){
		 for(String id:ids){
		    	this.mBaseDao.executeSql(" update  "+this.mBaseDao.tableName(BaseGoods.class)+" set status=1 where id_='"+id+"'", null);
		  }
		return R.ok();
	}
	
	/**
	 * 上下架操作
	 */
	@RequestMapping("/startOrStopSell")
	@RequiresPermissions("sp:goods:update")
	public R startOrStopSell(@RequestBody Map m){
		JSONArray o=(JSONArray) m.get("ids");
		Object[] ids = o.toArray();
		Integer goodsTypeId=(Integer)m.get("goodsTypeId");
		Integer isDown=(Integer)m.get("isDown");
		String tb=getGoodsTableName(Integer.valueOf(goodsTypeId));
		for(Object id:ids){
			if(isDown==0) {
				this.mBaseDao.executeSql(" update  "+tb+" set isDown="+isDown+",downTime=null where id_='"+id+"'", null);
			} else if(isDown==1){
				this.mBaseDao.executeSql(" update  "+tb+" set isDown="+isDown+",downTime=now() where id_='"+id+"'", null);
			}
		}
		return R.ok();
	}
}
